﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Shared.Infrastructure.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Shared.Infrastructure.Extensions
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection AddSharedInfrastructure(this IServiceCollection services)
        {
            services.AddControllers()
                .ConfigureApplicationPartManager(manager =>
            {
                manager.FeatureProviders.Add(new InternalControllerFeatureProvider());
            });
            return services;
        }

        public static IServiceCollection AddDatabaseContext<T>(this IServiceCollection services,IConfiguration configuration) where T:DbContext {
            var conStr = configuration.GetConnectionString("DefaultConnection");
            services.AddMSSQL<T>(conStr);
            return services;
        }

        private static IServiceCollection AddMSSQL<T>(this IServiceCollection services,string connectionStr) where T:DbContext 
        {
            services.AddDbContext<T>(p=>p.UseSqlServer(connectionStr));
            using var scope=services.BuildServiceProvider().CreateScope();
            var dbcontext= scope.ServiceProvider.GetRequiredService<T>();
            dbcontext.Database.Migrate();
            return services;
        }
    }
}
